<template>
  <div class="recycle-bin-container">
    <div class="action-bar">
      <el-button
          class="action-btn-clear"
          @click="clearRecycleBin"
          :icon="Delete"
      >
        清空回收站
      </el-button>
      <el-button
          class="action-btn-clear"
          @click="batchDeleteFiles"
          :icon="Delete"
          :disabled="!selectedFiles.length"
      >
        删除
      </el-button>
      <el-button
          class="action-btn-recover"
          @click="restoreSelectedFiles"
          :icon="Refresh"
          :disabled="!selectedFiles.length"
      >
        恢复
      </el-button>
      <div class="tip">
        提示：回收站不占用网盘空间，文件保存 10 天后将被自动清除。
        <a href="#" @click="upgradeToSuperMember">开通会员</a> 延长至30天
      </div>
    </div>
    <div class="breadcrumb">
      <span>回收站</span>
    </div>
    <el-table
        :data="recycleBinFiles"
        class="file-table"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="文件名">
        <template #default="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column prop="size" label="大小">
        <template #default="scope">
          {{ formatFileSize(scope.row.size) }}
        </template>
      </el-table-column>
      <el-table-column prop="deletedTime" label="删除时间">
        <template #default="scope">
          {{ formatDate(scope.row.deletedTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="remainingTime" label="有效时间">
        <template #default="scope">
          {{ scope.row.remainingTime }}天
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button
              type="danger"
              size="small"
              @click="deleteFile(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import { Delete, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'


const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
const files = ref([]) // 存储文件列表
const folders = ref([]) // 存储文件夹列表
const isLoading = ref(false) // 加载状态标识

// 模拟回收站文件数据
const recycleBinFiles = ref([
  { id: 1, name: '文档1.docx', type: 'document', size: 1024 * 15, deletedTime: '2023-05-10', remainingTime: 10 },
  { id: 2, name: '图片1.jpg', type: 'image', size: 1024 * 1024 * 2, deletedTime: '2023-05-12', remainingTime: 10 },
  { id: 3, name: '视频1.mp4', type: 'video', size: 1024 * 1024 * 100, deletedTime: '2023-05-15', remainingTime: 10 },
])
// 存储选中的文件
const selectedFiles = ref([])

// 获取文件列表
const fetchFiles = async (username) => {
  isLoading.value = true
  try {
    const response = await axios.get('/api/recycleFiles', {
      params: { username}
    })
    if (response.status === 200) {
      files.value = response.data.files || []
      folders.value = response.data.folders || []
    } else {
      ElMessage.error('获取文件列表失败')
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('获取文件列表失败')
  } finally {
    isLoading.value = false
  }
}
// 在组件挂载时加载文件列表
onMounted(() => {
  fetchFiles(userInfo.username) // 传入当前用户的用户名
})

// 处理选中变化
const handleSelectionChange = (selection) => {
  selectedFiles.value = selection
}

// 清空回收站
const clearRecycleBin = () => {
  ElMessageBox.confirm('确定要清空回收站吗？此操作不可恢复。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {

    ElMessage.success('回收站已清空')
  }).catch(() => {
    // 取消操作
  })
}
//删除单个文件
const deleteFile = (file) => {
  ElMessageBox.confirm(`确定要删除 "${file.name}" 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟从列表中移除
    const index = recycleBinFiles.value.findIndex(f => f.id === file.id)
    if (index !== -1) {
      recycleBinFiles.value.splice(index, 1)
    }
    ElMessage.success('文件已删除')
  }).catch(() => {
    // 取消操作
  })
}
//批量删除文件
const batchDeleteFiles = () => {
  if (!selectedFiles.value.length) {
    ElMessage.warning('请先选择文件')
    return
  }
  const count = selectedFiles.value.length
  ElMessageBox.confirm(
      `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 从列表中移除选中的文件
    recycleBinFiles.value = recycleBinFiles.value.filter(
        file => !selectedFiles.value.some(selected => selected.id === file.id)
    )
    selectedFiles.value = [] // 清空选中状态
    ElMessage.success(`已删除 ${count} 个文件`)
  }).catch(() => {
    // 取消操作
  })
}
// 恢复选中的文件
const restoreSelectedFiles = () => {
  if (!selectedFiles.value.length) return
  ElMessageBox.confirm(`确定要恢复选中的 ${selectedFiles.value.length} 个文件吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    const restoredFiles = selectedFiles.value.map(file => {
      const index = recycleBinFiles.value.findIndex(f => f.id === file.id)
      if (index !== -1) {
        recycleBinFiles.value.splice(index, 1)
      }
      return file
    })

    selectedFiles.value = []
    ElMessage.success(`已恢复 ${restoredFiles.length} 个文件`)
  }).catch(() => {
    // 取消操作
  })
}
const formatFileSize = (bytes) => {
  if (bytes === 0) return '空'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString()
}

const upgradeToSuperMember = () => {
  // 实现开通会员逻辑
  ElMessage.success('已跳转到开通会员页面')
}
</script>

<style scoped>
.recycle-bin-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.action-btn-clear {
  padding: 8px 15px;
  margin-right: 20px;
  background-color: #ff4757;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.action-btn-recover {
  padding: 8px 15px;
  margin-right: 20px;
  background-color: #75d368;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.action-btn:hover {
  background-color: #e84118;
}

.tip {
  color: #666;
  font-size: 14px;
}

.tip a {
  color: #3498db;
  text-decoration: none;
}

.tip a:hover {
  text-decoration: underline;
}

.breadcrumb {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: bold;
  color:black;
}

.file-table {
  width: 100%;
  table-layout: fixed;
}

.file-table .el-table__header th,
.file-table .el-table__body td {
  text-align: left;
  padding: 10px;
  word-break: break-word;
}

.file-table tr:hover {
  background-color: #c7dfef;
}

</style>